package com.landcode.netty.handler;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import com.landcode.netty.util.ChannelUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractMqttHandler extends SimpleChannelInboundHandler<MqttMessage>{
	
	protected ConcurrentHashMap<String, Channel> mqttChannels = new ConcurrentHashMap<>();
	
	protected  abstract void doMessage(ChannelHandlerContext ctx, MqttMessage mqttMessage);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception {
        log.info("建立连接，名称为【{}】", ctx.name());
        MqttFixedHeader mqttFixedHeader = msg.fixedHeader();
        Optional.ofNullable(mqttFixedHeader)
                .ifPresent( t -> doMessage(ctx, msg));
    }

    //连接关闭
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //判断是否登录
        Channel channel = ctx.channel();
        String deviceSn = ChannelUtil.getDeviceSn(channel);
        if(StringUtils.isBlank(deviceSn)) {
            log.info("===设备号为空===");
            return;
        }else {
            
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
